# -*- coding: utf-8 -*-
# @Time : 2021/2/9 15:55
# @Author : zhangcheng
# @Software: PyCharm

from tornado.web import RequestHandler
from init.init import dbsession, whitelist


class BaseHandler(RequestHandler):
    # 每次接口请求完毕以后关闭数据库连接
    def __init__(self, *args, **kwargs):
        super(BaseHandler, self).__init__(*args, **kwargs)

    def set_default_headers(self) -> None:
        # 解决跨域访问
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers", "x-request-with")
        self.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
        self.set_header("Access-Control-Max-Age", 1000)
        self.set_header("Content-type", "application/json")

    def prepare(self):
        # 设置访问拦截，只有白名单里的域名可以访问接口，否则返回403
        if self.request.host_name not in whitelist:
            self.set_status(403)
            self.write({"message": "访问接口权限不足", "error": "权限不足"})
            self.finish()

    def on_finish(self):
        dbsession.close()

    def options(self):
        self.set_status(204)
        self.finish()
